
/**
** \file       simple_cmd.c
**
** \brief      this function parse the simple_command rule
**
** \author     Ben M'rad Hanna, Laterem Hamza, Boillot Ulysse
**             and De Olivera Guillaume
**
** \version    0.8
**
** \date       26 Novembre 2010
**
*/

#include "rules.h"

static s_smp_cmd        *init(s_smp_cmd                 *smp_cmd)
{
  smp_cmd->elt = calloc(1, sizeof (s_element));

  return (smp_cmd);
}

static s_smp_cmd        *rule_simple_command1(s_smp_cmd *smp_cmd)
{
  s_prefix              *tmp_prefix = NULL;
  s_element             *tmp_elt = NULL;

  tmp_prefix = smp_cmd->prefix;
  tmp_elt = smp_cmd->elt;

  while (rule_prefix(tmp_prefix) != NULL)
  {
    tmp_prefix->next = calloc(1, sizeof (s_prefix));
    tmp_prefix = tmp_prefix->next;
  }

  while (rule_element(tmp_elt) != NULL)
  {
    tmp_elt->next = calloc(1, sizeof (s_element));
    tmp_elt = tmp_elt->next;
  }

  return (smp_cmd);
}
static s_smp_cmd	*rule_scaux(s_smp_cmd		*smp_cmd)
{
  free(smp_cmd->prefix);
  smp_cmd->prefix = NULL;
  free(smp_cmd->elt);
  smp_cmd->elt = NULL;

  return (NULL);

}

static s_smp_cmd        *rule_simple_command2(s_smp_cmd  *smp_cmd)
{
  s_element             *tmp_elt = NULL;
  s_element             *last_elt = NULL;

  tmp_elt = smp_cmd->elt;
  last_elt = tmp_elt;

  if (rule_element(tmp_elt) != NULL)
    {
      tmp_elt->next = calloc(1, sizeof (s_element));
      tmp_elt = tmp_elt->next;

      while (rule_element(tmp_elt) != NULL)
	{
	  last_elt = tmp_elt;
	  tmp_elt->next = calloc(1, sizeof (s_element));
	  tmp_elt = tmp_elt->next;
	}

      free(last_elt->next);
      last_elt->next = NULL;
      free(smp_cmd->prefix);
      smp_cmd->prefix = NULL;

      return (smp_cmd);
    }
  else
    return (rule_scaux(smp_cmd));
}

s_smp_cmd               *rule_simple_command(s_smp_cmd  *smp_cmd)
{

  if (g_data->lexer == NULL)
    return (NULL);

  smp_cmd = init(smp_cmd);

  if (rule_prefix(smp_cmd->prefix) != NULL)
  {
    rule_simple_command1(smp_cmd);
    return (smp_cmd);
  }
  else
  {
    if ((rule_simple_command2(smp_cmd)) != NULL)
      return (smp_cmd);
    else
    {
      free(smp_cmd->elt);
      smp_cmd->elt = NULL;

      return (NULL);
    }
  }
}
